package cz.ctu.guiproject.client.manager;

import android.util.Log;
import cz.ctu.guiproject.client.dispatcher.Dispatcher;
import cz.ctu.guiproject.client.dtos.ResponseState;
import cz.ctu.guiproject.client.messaging.DisconnectRequest;
import cz.ctu.guiproject.client.messaging.DisconnectResponse;
import cz.ctu.guiproject.client.messaging.InitResponse;
import static cz.ctu.guiproject.client.resources.constants.Logger.*;
import cz.ctu.guiproject.client.xml.XmlDecodeFactory;
import cz.ctu.guiproject.client.xml.XmlEncodeFactory;

public final class ConnectionManagerImpl implements ConnectionManager {

	private final Dispatcher dispatcher;
	private final JARManager jarManager;

	public ConnectionManagerImpl(Dispatcher dispatcher) {
		this.dispatcher = dispatcher;
		jarManager = JARManagerImpl.getInstance();
	}

	/* (non-Javadoc)
	 * @see cz.ctu.guiproject.client.manager.ConnectionManager#initClient(java.lang.String)
	 */
	@Override
	public boolean initClient(String xml) {
		final InitResponse initResponse = XmlDecodeFactory.decodeInitClient(xml);
		jarManager.downloadComponents(initResponse.getJarUrls());
		Log.i(TAG, initResponse.toString());
		return true;
	}

	/* (non-Javadoc)
	 * @see cz.ctu.guiproject.client.manager.ConnectionManager#forceDisconnect()
	 */
	@Override
	public void forceDisconnect() {
		// disconnect from server
		final DisconnectRequest disconnectRequest = new DisconnectRequest();
		final String disconnectRequestXML = XmlEncodeFactory.encodeDisconnectRequest(disconnectRequest);
		dispatcher.send(disconnectRequestXML);
	}

	/* (non-Javadoc)
	 * @see cz.ctu.guiproject.client.manager.ConnectionManager#disconnectClient(java.lang.String)
	 */
	@Override
	public void disconnectClient(String xml) {
		final DisconnectResponse disconnectResponse = XmlDecodeFactory.decodeDisconnectResponse(xml);
		if (disconnectResponse.getResponse() == ResponseState.ACCEPTED) {
			// TODO really disconnect client
			Log.i(TAG, "Now the client should be already disconnected!");
		}
	}
}
